<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 聊天室</title>
    <style>
        /* 设置按钮 */
        #settingsButton {
            background-color: #66FFB3;
            border: none;
            float: right;
        }
        /* 设置面板 */
        #settingsPanel {
            color: white;
            position: absolute;
            top: 10px;
            right: 10px;
            border: 1px solid #ddd;
            background-color: #fff;
            padding: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            background-color: #D15FEE;
        }

        #settingsPanel div {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <h1 style="margin: 0 auto; width: fit-content;margin-top: 40px;">WebSocket 聊天室</h1>
       <!-- 设置面板 -->
    <div id="settingsPanel">
        <div><strong>昵称:</strong> <span id="currentUsername">未知用户</span></div>
        <div><strong>消息颜色:</strong> <span id="currentColor" style="color: #ffffff;">#000000</span></div>
        <button id="settingsButton">更改</button>
    </div>
    <div id="messages" style="margin-top: 60px;border:1px solid #ddd; height:300px; overflow:auto; margin-bottom:10px;padding: 20px;"></div>

    <!-- 消息输入框 -->
    <textarea id="inputMessage" name="message" rows="7"  placeholder="请输入你的内容" style="width: 100%;background-color: rgb(247, 247, 247);"></textarea>
    <div style="float: right;">
        <button id="sendButton" style="background-color: #FF6EC7;color: white;">发送</button>
        <!-- 表情选择按钮 -->
        <button id="emojiButton">😀</button>
    </div>

    <!-- 表情选择面板 -->
    <div id="emojiPanel" style="display: none; position: absolute; border: 1px solid #ddd; background: #fff; padding: 10px;">
        <span class="emoji" style="cursor: pointer;">😀</span>
        <span class="emoji" style="cursor: pointer;">😂</span>
        <span class="emoji" style="cursor: pointer;">😍</span>
        <span class="emoji" style="cursor: pointer;">😢</span>
        <span class="emoji" style="cursor: pointer;">😎</span>
    </div>

  

 

    <script>
    const ws = new WebSocket('ws://localhost:3000'); // 连接 WebSocket 服务器
    const messagesDiv = document.getElementById('messages');
    const inputMessage = document.getElementById('inputMessage');
    const sendButton = document.getElementById('sendButton');
    const emojiButton = document.getElementById('emojiButton');
    const emojiPanel = document.getElementById('emojiPanel');
    const settingsButton = document.getElementById('settingsButton');
    const currentUsername = document.getElementById('currentUsername');
    const currentColor = document.getElementById('currentColor');

    // 使用 URLSearchParams 获取 URL 查询参数
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username') ? urlParams.get('username') : "未知用户"; // 获取 'username' 参数的值
    const userColor = urlParams.get('color') ? urlParams.get('color') : getRandomColor(); // 获取 'userColor' 参数的值

    // 更新设置面板中的昵称和颜色
    currentUsername.textContent = username;
    currentColor.textContent = userColor;
    currentColor.style.backgroundColor = userColor;

    // 随机生成颜色
    function getRandomColor() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    // 获取当前时间
    function getNowFormatDate() {
        let currentDate = new Date();
        let year = currentDate.getFullYear();
        let month = currentDate.getMonth() + 1;
        let date = currentDate.getDate();
        let hours = currentDate.getHours();
        let minutes = currentDate.getMinutes();
        let seconds = currentDate.getSeconds();
        return `<span style="color: grey;font-size:12px;">${year}-${month}-${date} ${hours}:${minutes}:${seconds}</span>`;
    }

    // 监听服务器发送的消息
    ws.onmessage = (event) => {
        const newMessage = document.createElement('div');

        if (typeof(event.data) === "string") {
            newMessage.innerHTML = `<div style="margin:0 auto;width: fit-content;font-size:14px;color:grey;line-height:1.5;">${event.data} ${getNowFormatDate()}</div>`;
        } else {
            event.data.text().then((text) => {
                const messageData = JSON.parse(text);
                const user = messageData.username;
                const message = messageData.message;
                var color = messageData.userColor;
                newMessage.innerHTML = `<div style="color: ${color}; font-size:14px;">
                    ${user}: ${message} ${getNowFormatDate()}</div>`;
            });
        }

        messagesDiv.appendChild(newMessage);
        messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
    };

    // 监听发送按钮点击事件
    sendButton.addEventListener('click', () => {
        const message = inputMessage.value.trim();

        if (message && username) {
            const messageData = {
                username: username,
                message: message,
                userColor:userColor,
            };

            // 将消息对象转换为 JSON 字符串并发送
            ws.send(JSON.stringify(messageData));

            const selfMessage = document.createElement('div');
            selfMessage.innerHTML = `<div style="color: ${userColor}; font-size:14px;">
                你 (${username}): ${message} ${getNowFormatDate()}</div>`;
            messagesDiv.appendChild(selfMessage);
            inputMessage.value = ''; // 清空输入框
        } 
    });

    // 监听连接打开
    ws.onopen = () => {
        console.log('已连接到服务器');
    };

    // 监听连接关闭
    ws.onclose = () => {
        console.log('与服务器断开连接');
    };

    // 监听错误
    ws.onerror = (error) => {
        console.error('WebSocket 错误:', error);
    };

    // 显示/隐藏表情选择面板
    emojiButton.addEventListener('click', () => {
        emojiPanel.style.display = (emojiPanel.style.display === 'none') ? 'block' : 'none';
    });

    // 将选中的表情插入到输入框
    emojiPanel.addEventListener('click', (event) => {
        if (event.target.classList.contains('emoji')) {
            inputMessage.value += event.target.textContent; // 插入表情
            emojiPanel.style.display = 'none'; // 隐藏表情面板
        }
    });

    // 显示/隐藏设置面板
    settingsButton.addEventListener('click', () => {
        window.location.href = `login.html?username=${username}&userColor=${userColor}`; // 刷新页面
    });
    </script>
</body>
</html>
